package nl.hanze.designpatterns.db;

import java.sql.*;
import java.util.*;

public class Executor {

    private static Executor _instance = null;
    private static final String connectionURL = "jdbc:mysql://localhost/dp?user=root";
    private static final String sqlDriver = "com.mysql.jdbc.Driver";

    private Executor () {
        loadDBDriver();
    }

    private synchronized static void createInstance () {
        if (_instance == null) _instance = new Executor ();
    }

    public static Executor getInstance () {
        if (_instance == null) createInstance ();
        return _instance;
    }

    private static void loadDBDriver() {
        try {
            Class.forName(sqlDriver).newInstance();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private static Connection getConnection() throws SQLException{
        return DriverManager.getConnection(connectionURL);
    }

    private static ResultSet performQuery(String query) throws SQLException {
        Connection conn = getConnection();
        Statement stmt = conn.createStatement() ;
        return stmt.executeQuery(query) ;
    }

	public static void executeQuery(String query) throws SQLException {
        performQuery(query);
	}

    public static void executeChange(String query) throws SQLException {
        Connection conn = getConnection();
        Statement stmt = conn.createStatement() ;
        stmt.execute(query) ;
    }
	
	public static <T> Iterator<T> getIterator(Class<T> c, String query) throws SQLException {
		return new RowIterator<T>(c, performQuery(query));
	}
}
